package com.swipemaster;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

public class Square
{
    /** Buffer holding the vertices. */
    private FloatBuffer mVertexBuffer; 
    /** Position. */
    private int mX, mY;
    /** Direction of move vector. */
    private int mXDirection = 1, mYDirection = 1;
    /** Color. */
    private float mRed, mGreen, mBlue;

    private float mVertices[] = 
    { 
        -1, 1, 0,   
        -1, -1, 0,    
        1, 1, 0,  
        1, -1, 0     
    };

    public Square(int size, float red, float green, float blue)
    {
        mRed = red;
        mGreen = green;
        mBlue = blue;
        
        for (int i = 0; i < mVertices.length; i++)
        {
            mVertices[i] *= size;
        }
        
        // Float has 4 bytes so we allocate for each coordinate 4 bytes.
        ByteBuffer vertexByteBuffer = ByteBuffer.allocateDirect(mVertices.length * 4);
        vertexByteBuffer.order(ByteOrder.nativeOrder());

        // Allocates the memory from the byte buffer.
        mVertexBuffer = vertexByteBuffer.asFloatBuffer();

        // Fill the mVertexBuffer with the mVertices.
        mVertexBuffer.put(mVertices);

        // Set the cursor position to the beginning of the buffer.
        mVertexBuffer.position(0);
    }

    /** The draw method for the square with the GL context */
    public void draw(GL10 gl)
    {
        gl.glPushMatrix();

        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        
        // Move the square.
        gl.glTranslatef(mX, mY, 0);

        // Set the color for the square.
        gl.glColor4f(mRed, mGreen, mBlue, 0.5f);

        // Point to our vertex buffer.
        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);

        // Draw the mVertices as triangle strip.
        gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, mVertices.length / 3);
        
        // Disable the client state before leaving.
        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
        
        gl.glPopMatrix();
    }
    
    public void setXAndY(int x, int y)
    {
        mX = x;
        mY = y;
    }

    public void move()
    {
        mX = mX + mXDirection;
        if (mX >= GameRenderer.mScreenWidth || mX <= 0)
        {
            mXDirection = -mXDirection;
        }
        
        mY = mY + mYDirection;
        if (mY >= GameRenderer.mScreenHeight || mY <= 0)
        {
            mYDirection = -mYDirection;
        }
    }
}
